import AD from "../../common/ad.js"
import Globalunit from "../../common/globalunit.js";
import uniShare from 'uni_modules/uni-share/js_sdk/uni-share.js';
export default {
	data() {
		return {
			adpid: 0,
			canlingqu: 10,
			innerAudioContext: null,
			allsong: 0,
			audioPlay: true,
			hongbaodialog: false,
			hongbao: 0,
			hblist: [],
			videodialog: false,
			caigejieguo: false,
			timer: null,
			time: 3,
			uid: '',
			token: "",
			user: {
				"coin": 0,
				"index": 1,
				"fen": 0,
				"leijicaiduigequ": 0,
				"tixiancaidui": 0,
				"liandui": 0,
				"leijiliandui": 0
			},
			songinfo: {
				url: "",
				daan1: "",
				daan2: "",
				daan3: "",
				_id: ""
			},
			nowtime: 0,
			timer1: null,
			hongbaocoin: 0,
			height: 0,
			videofanbei: {
				"min": 1,
				"max": 5
			},
			lianduijiangli: {
				"song": 0,
				"fen": 0
			}
		}
	},
	beforeDestroy() {
		this.innerAudioContext.destroy();
	},
	onLoad() {
		var self = this
		self.adpid = Globalunit.banneradpid
		uni.getSystemInfo({
			//成功获取的回调函数，返回值为系统信息
			success: (sysinfo) => {
				var height = sysinfo.statusBarHeight
				if (height < 44) {
					height = 22
				}
				self.height = height + 'px'
			},
			complete: () => {}
		});
		// 可选预加载数据
		AD.load(Globalunit.adpid)

		uni.getStorage({
			key: 'uni_id_token',
			success: function(res) {
				console.log(res.data);
				self.token = res.data
			}
		});
		uni.getStorage({
			key: 'uid',
			success: function(res) {
				console.log(res.data);
				self.uid = res.data
				self.loadsong()
			}
		});
		this.nowtime = Math.floor(Date.now() / 1000)
		if (!self.timer1) {
			self.timer1 = setInterval(function() {
				if (self.hblist.length > 0) {
					self.changehongbao1(self.hblist)
				}
			}, 1000)
		}
	},
	onShow() {
		var self = this
		uni.getStorage({
			key: 'uni_id_token',
			success: function(res) {
				console.log(res.data);
				self.token = res.data
			}
		});
		uni.getStorage({
			key: 'uid',
			success: function(res) {
				console.log(res.data);
				self.uid = res.data
				self.loadsong(true)
			}
		});
	},
	onHide() {
		if (this.innerAudioContext != null) {
			this.innerAudioContext.destroy()
		}
	},
	methods: {
		toshare() {
			uniShare({
				content: { //公共的分享参数配置  类型（type）、链接（herf）、标题（title）、summary（描述）、imageUrl（缩略图）
					type: 0,
					href: 'https://m3w.cn/yjcg',
					title: '有奖猜歌，邀你一起猜歌啦',
					summary: '歌曲猜不停，与喜欢的音乐不期而遇',
					imageUrl: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-c26ec39a-f602-435d-b8bb-0453aa221eb0/3c86a0c1-a9e5-4e5f-8b1d-5bfc0b53a4ca.png'
				},
				menus: [
					{
						"img": "/static/app-plus/sharemenu/wechatfriend.png",
						"text": "微信好友",
						"share": { //当前项的分享参数配置。可覆盖公共的配置如下：分享到微信小程序，配置了type=5
							"provider": "weixin",
							"scene": "WXSceneSession"
						}
					},
					{
						"img": "/static/app-plus/sharemenu/wechatmoments.png",
						"text": "微信朋友圈",
						"share": {
							"provider": "weixin",
							"scene": "WXSenceTimeline"
						}
					},
					/* {
						"img": "/static/app-plus/sharemenu/mp_weixin.png",
						"text": "微信小程序",
						"share": {
							provider: "weixin",
							scene: "WXSceneSession",
							type: 5,
							miniProgram: {
								id: '123',
								path: '/pages/list/detail',
								webUrl: '/#/pages/list/detail',
								type: 0
							},
						}
					}, */
					{
						"img": "/static/app-plus/sharemenu/weibo.png",
						"text": "微博",
						"share": {
							"provider": "sinaweibo"
						}
					},
					{
						"img": "/static/app-plus/sharemenu/qq.png",
						"text": "QQ",
						"share": {
							"provider": "qq"
						}
					},
					{
						"img": "/static/app-plus/sharemenu/copyurl.png",
						"text": "复制",
						"share": "copyurl"
					},
					{
						"img": "/static/app-plus/sharemenu/more.png",
						"text": "更多",
						"share": "shareSystem"
					}
				],
				cancelText: "取消分享",
			}, e => { //callback
				console.log(e);
			})
		},
		// 音频播放暂停
		audioPlayFn(play) {
			let {
				innerAudioContext
			} = this
			if (play) {
				innerAudioContext.play()
			} else {
				innerAudioContext.pause()
			}
		},
		gomine() {
			uni.reLaunch({
				url: '/pages/mine/mine',
			});
		},
		contextInit() {
			let that = this;
			let innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = that.songinfo['url'];
			innerAudioContext.loop = true;
			that.innerAudioContext = innerAudioContext
		},
		
		closehuodetixian() {
			var self = this
			self.$refs.huodetixian.close()
			self.loadsong()
		},
		closepopup() {
			var self = this
			self.$refs.popup.close()
			self.loadsong()
		},
		closecaigepopup() {
			var self = this
			if (self.time <= 0) {
				self.$refs.caigepopup.close()
				self.loadsong()
			}
		},
		opencaigepopup() {
			var self = this
			self.time = 3
			if (self.timer != null) {
				clearInterval(self.timer)
			}
			self.$refs.caigepopup.open()
			self.timer = setInterval(function() {
				self.time--
				if (self.time < 0) {
					clearInterval(self.timer)
				}
			}, 1000)
		},
		loadsong(show) {
			var self = this
			if (!show) {
				uni.showLoading({
					title: '处理中...'
				})
			}
			uniCloud.callFunction({
				name: 'hallctrl',
				data: {
					action: "hall/getsong",
					data: {
						uid: self.uid,
						uniIdToken: self.token
					}
				}
			}).then((res) => {
				uni.hideLoading()
				if (res.result.code && res.result.code != 0) {
					uni.showToast({
						title: res.result.message,
						icon: 'none',
					});
					return
				}
				if (res.result.errcode && res.result.errcode != 0) {
					uni.showToast({
						title: res.result.errmsg,
						icon: 'none',
					});
					return
				}
				self.videofanbei = res.result.data.videofanbei
				self.lianduijiangli = res.result.data.lianduijiangli
				self.user = res.result.data.user
				self.allsong = res.result.data.needsong
				self.songinfo = res.result.data.song
				if (self.innerAudioContext != null) {
					self.innerAudioContext.destroy()
				}
				self.contextInit();
				// console.log('红包', res.result.data.hongbao)
				self.changehongbao(res.result.data.hongbao)
			}).catch((err) => {
				console.log("err: ", err);
				uni.hideLoading()
				uni.showToast({
					title: "获取失败，请稍后重试!",
					icon: 'none',
				});
			})
		},

		dati(index) {
			var self = this
			// self.$refs.huodetixian.open()
			// return
			console.log(index)
			self.innerAudioContext.pause()
			uni.showLoading({
				title: '处理中...'
			})
			uniCloud.callFunction({
				name: 'hallctrl',
				data: {
					action: "hall/dati",
					data: {
						uid: self.uid,
						uniIdToken: self.token,
						daan: index,
						id: self.songinfo._id
					}
				}
			}).then((res) => {
				uni.hideLoading()
				console.log('获取歌曲', res)
				if (res.result.code && res.result.code != 0) {
					uni.showToast({
						title: res.result.message,
						icon: 'none',
					});
					return
				}
				if (res.result.errcode && res.result.errcode != 0) {
					uni.showToast({
						title: res.result.errmsg,
						icon: 'none',
					});
					return
				}
				self.user = res.result.data.user
				self.caigejieguo = res.result.data.result == 'error' ? false : true
				if (res.result.data.tixianjihui) {
					self.$refs.huodetixian.open()
				} else {
					self.hongbao = res.result.data.hongbao
					if (res.result.data.hongbaotype == "liandui") {
						self.$refs.popup.open()
					} else {
						self.opencaigepopup()
					}

				}
			}).catch((err) => {
				console.log("err: ", err);
				uni.hideLoading()
				self.innerAudioContext.play();
				uni.showToast({
					title: "答题失败，请重试!",
					icon: 'none',
				});
			})
		},
		showAd(index) {
			var self = this
			uni.showLoading({
				title: '处理中...'
			})
			uniCloud.callFunction({
				name: 'hallctrl',
				data: {
					action: "hall/getvideocount",
					data: {
						uid: self.uid,
						uniIdToken: self.token,
					}
				}
			}).then((res) => {
				uni.hideLoading()
				if (res.result.code && res.result.code != 0) {
					uni.showToast({
						title: res.result.message,
						icon: 'none',
					});
					return
				}
				if (res.result.errcode && res.result.errcode != 0) {
					uni.showToast({
						title: res.result.errmsg,
						icon: 'none',
					});
					return
				}
				AD.show(Globalunit.adpid, (res) => {
					console.log("onclose")
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束
						console.log("onClose " + res.isEnded);
						// 1猜对 奖励3-5倍  2 猜错复活  3 红包3-5倍
						self.adcallback(index)
					} else {
						// 播放中途退出
						console.log("onClose " + res.isEnded);
					}
					// 可选预加载下一条广告数据，减少加载等待时间，调用此 API 不会显示loading，不影响业务
					AD.load(Globalunit.adpid)
				}, (err) => {
					// 广告无法显示，输出错误信息
					console.log(err) // {code: code, errMsg: message}
					uni.showToast({
						title: '广告播放错误',
						icon: 'none',
					});
				})
			}).catch((err) => {
				console.log("err: ", err);
				uni.hideLoading()
			})

		},
		adcallback(index) {
			var self = this
			var type = null
			if (index == 1) {
				type = "caiduijiangli"
			} else if (index == 2) {
				type = "fuhuo"
			} else if (index == 3) {
				type = "hongbaofanbei"
			}
			uni.showLoading({
				title: '处理中...'
			})
			uniCloud.callFunction({
				name: 'hallctrl',
				data: {
					action: "hall/videocallback",
					data: {
						uid: self.uid,
						uniIdToken: self.token,
						type: type
					}
				}
			}).then((res) => {
				uni.hideLoading()
				if (res.result.code && res.result.code != 0) {
					uni.showToast({
						title: res.result.message,
						icon: 'none',
					});
					return
				}
				if (res.result.errcode && res.result.errcode != 0) {
					uni.showToast({
						title: res.result.errmsg,
						icon: 'none',
					});
					return
				}
				self.user = res.result.data.user
				self.loadsong()
				if (index == 1 || index == 2) {
					self.$refs.caigepopup.close()
				} else {
					self.$refs.hongbaopopup.close()
				}
				if (index == 1 || index == 3) {
					var title = '恭喜获得' + res.result.data.beishu + '倍奖励，' + res.result.data.num
					if (res.result.data.jianglitype == 'coin') {
						title = title + '金币'
					} else {
						title = title + '元'
					}
					uni.showToast({
						title: title,
						icon: 'none',
					});
				}
			}).catch((err) => {
				console.log("err: ", err);
				uni.hideLoading()
			})

		},
		howplay() {
			var self = this
			uni.navigateTo({
				url: '/pages/play/play',
			});
		},


		closehongbaopopup() {
			var self = this
			self.$refs.hongbaopopup.close()
		},
		changehongbao(data) {
			var self = this
			var count = 0
			var list = []
			var now = Math.floor(Date.now() / 1000);
			for (var i = 1; i <= 10; i++) {
				var item = data['red' + i]
				item['index'] = i
				var time = item.lingqu + (item.time) * 60 - now
				item.chai = self.gettime(time)
				list.push(item)
				if (item.lingqu + item['time'] * 60 < now || item.lingqu == 0) {
					count += 1
				}
			}
			self.canlingqu = count
			self.hblist = list
		},
		changehongbao1() {
			var self = this
			var count = 0
			var list = []
			var now = Math.floor(Date.now() / 1000);
			for (var i = 1; i <= 10; i++) {
				var item = self.hblist[i - 1]

				var time = item.lingqu + (item.time) * 60 - now
				item.chai = self.gettime(time)
				list.push(item)
				if (item.lingqu + item['time'] * 60 < now || item.lingqu == 0) {
					count += 1
				}
			}
			self.canlingqu = count
			self.hblist = list
		},
		chaihongbao() {
			var self = this
			self.time = 3
			if (self.timer != null) {
				clearInterval(self.timer)
			}
			self.$refs.hongbaopopup.open()
			self.timer = setInterval(function() {
				self.time--
				if (self.time < 0) {
					clearInterval(self.timer)
				}
			}, 1000)
		},
		linghongbao(item) {
			var self = this
			uni.showLoading({
				title: '处理中...'
			})
			uniCloud.callFunction({
				name: 'hallctrl',
				data: {
					action: "hall/linghongbao",
					data: {
						uid: self.uid,
						uniIdToken: self.token,
						index: item.index,
					}
				}
			}).then((res) => {
				uni.hideLoading()
				if (res.result.code && res.result.code != 0) {
					uni.showToast({
						title: res.result.message,
						icon: 'none',
					});
					return
				}
				if (res.result.errcode && res.result.errcode != 0) {
					uni.showToast({
						title: res.result.errmsg,
						icon: 'none',
					});
					return
				}
				self.user = res.result.data.user
				self.hongbaocoin = res.result.data.coin
				self.changehongbao(res.result.data.hongbao)
				self.chaihongbao()
			}).catch((err) => {
				console.log("err: ", err);
				uni.hideLoading()
				uni.showToast({
					title: "领取失败，请稍后重试!",
					icon: 'none',
				});
			})
		},
		gettime(value) {
			if (!value) return '';
			if (value < 0) {
				return '拆开'
			}
			let hh = parseInt(value / 3600); //小时
			let shh = value - hh * 3600;
			let ii = parseInt(shh / 60);
			let ss = shh - ii * 60;
			return (hh < 10 ? '0' + hh : hh) + ':' + (ii < 10 ? '0' + ii : ii) + ':' + (ss < 10 ? '0' + ss : ss);
		},
		onload(e) {
			console.log("onload");
		},
		onclose(e) {
			console.log("onclose: " + e.detail);
		},
		onerror(e) {
			console.log("onerror: " + e.detail.errCode + " message:: " + e.detail.errMsg);
		}
	}
}
